package pkg

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"srv/config"
	"srv/internal/dao"
	pb "srv/proto"

	"strconv"
)

func SyncEs(d *dao.Doctor) {
	data, err := json.Marshal(d)
	if err != nil {
		log.Fatalf("Error marshaling document: %s", err)
	}

	// Set up the request object.
	req := esapi.IndexRequest{
		Index:      "doctor",
		DocumentID: strconv.Itoa(int(d.ID + 1)),
		Body:       bytes.NewReader(data),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), config.ES)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
}

func ESList() []*pb.DoctorList {
	var buf bytes.Buffer
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match_all": map[string]interface{}{},
		},
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	es := config.ES
	// Perform the search request.
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("test"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	var r map[string]interface{}
	var List []*pb.DoctorList
	json.NewDecoder(res.Body).Decode(&r)
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		s := hit.(map[string]interface{})["_source"].(map[string]interface{})

		list := pb.DoctorList{
			Name:          s["Name"].(string),
			Image:         s["Image"].(string),
			Hospital:      s["Hospital"].(string),
			Root:          s["Room"].(string),
			Nickname:      s["Nickname"].(string),
			Type:          int64(s["Type"].(float64)),
			RegisterPrice: float32(s["RegisterPrice"].(float64)),
			InspectPrice:  float32(s["InspectPrice"].(float64)),
			Intro:         s["Intro"].(string),
			Id:            int64(s["Id"].(float64)),
		}
		List = append(List, &list)
	}
	return List
}
